<script setup lang="ts">
import CustomNavbar from '@/pages/index/components/CustomNavbar.vue'
import XtxSwiper from '@/components/XtxSwiper.vue';
import CategoryPanel from '@/pages/index/components/CategoryPanel.vue';
import HotPanel from '@/pages/index/components/HotPanel.vue';

import { getHomeBannerAPI, getHomeCategoryAPI, getHomeHotAPI } from '@/services/home';
import { onLoad, onShow } from '@dcloudio/uni-app'
import { ref } from 'vue';
import type { BannerItem, CategoryItem, HotItem } from '@/types/home';
import XtxGuess from '@/components/XtxGuess.vue';
import type { XtxGuessInstance } from '@/types/components';
import PageSkeleton from '@/pages/index/components/PageSkeleton.vue';
import { useGuessList } from '@/composables';

const bannerList = ref<BannerItem[]>([])
const categoryList = ref<CategoryItem[]>([])
const hotList = ref<HotItem[]>([])
const getHomeBannerData = async () => {
  const res = await getHomeBannerAPI()
  console.log('res', res);
  bannerList.value = res.result
}

const getHomeCategoryData = async () => {
  const res = await getHomeCategoryAPI()
  console.log('res', res);
  categoryList.value = res.result
}

const getHomeHotData = async () => {
  const res = await getHomeHotAPI()
  console.log('res', res);
  hotList.value = res.result
}

// // 调用猜你喜欢的组件
// const guessRef = ref<XtxGuessInstance>()
// // 滚动触底
// const onScrolltolower = () => {
//   console.log('滚动触底');
//   guessRef.value?.getHomeGoodsGuessLikeData()
// }

const { guessRef, onScrolltolower } = useGuessList()

const isTriggered = ref(false)
// 自定义下拉刷新
const onRefresh = async () => {
  isTriggered.value = true
  // 重置猜你喜欢数据
  guessRef.value?.resetData()
  // 重新获取数据
  await Promise.all([
    getHomeBannerData(),
    getHomeCategoryData(),
    getHomeHotData(),
    guessRef.value?.getHomeGoodsGuessLikeData()
  ])

  isTriggered.value = false
}

const isLoading = ref(false)
onLoad(async () => {
  isLoading.value = true
  await Promise.all([
    getHomeBannerData(),
    getHomeCategoryData(),
    getHomeHotData(),
  ])

  isLoading.value = false
})
</script>

<template>
  <CustomNavbar />
  <!-- 滚动容器 -->
  <scroll-view refresher-enabled @refresherrefresh="onRefresh" :refresher-triggered="isTriggered"
    @scrolltolower="onScrolltolower" class="scroll-view" scroll-y>
    <PageSkeleton v-if="isLoading" />
    <template v-else>
      <XtxSwiper :banners="bannerList" />
      <CategoryPanel :categories="categoryList" />
      <HotPanel :hotList="hotList" />
      <XtxGuess ref="guessRef" />
    </template>
  </scroll-view>
</template>


<style lang="scss">
page {
  background-color: #f7f7f7;
  height: 100%;
  display: flex;
  flex-direction: column;
}

.scroll-view {
  flex: 1;
}
</style>
